<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\OfPatentNoticeService;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

/**
 * 通知书管理-控制器
 * @author 牧羊人
 * @since: 2021/12/28
 * Class Ofpatentnotice
 * @package app\admin\controller
 */
class Ofpatentnotice extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2021/12/28
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model       = new \app\admin\model\OfPatentNotice();
        $this->service     = new OfpatentnoticeService();
        $this->monitor     = new \app\admin\service\OfPatentMonitorService();
        $this->patentModel = new \app\admin\model\OfPatent();
        $this->tradeModel  = new \app\admin\model\OfTrademark();
    }

    /**
     * 首页数据
     *
     */
    public function index()
    {
        $param = request()->param();

        $patent_id = isset($param['patent_id']) ? $param['patent_id'] : 0;
        $type      = isset($param['type']) ? $param['type'] : 1;

        if (IS_POST) {
            $result = $this->service->getList();
            foreach ($result['data'] as $key => $value) {
                if ($type == 1) {
                    $result['data'][$key]['status'] = config('admin.patentnotice_status_2')[$value['status']];
                } elseif ($type == 2) {
                    $result['data'][$key]['status'] = config('admin.patentnotice_rademark_status')[$value['status']];
                }

            }
            return $result;
        }

        View::assign("patent_id", $patent_id);
        View::assign("type", $type);
        //从专利或者商标点击过来的时候 绑定到edit的 数据 name 弹窗提示新增到哪个
        $win_name = "";
        if ($type == 1) {
            $win_name = Db::name("of_patent")->where('id', $patent_id)->value("patent_name");
        } elseif ($type == 2) {
            $win_name = Db::name("of_trademark")->where('id', $patent_id)->value("brand_name");
        } elseif ($type == 3) {
            $win_name = ''; //著作权不知道哪个是名字
        }
        View::assign("win_name", $win_name);

        // 取消模板布局
        $this->app->view->layout(false);
        // 默认参数
        $data = func_get_args();
        if (isset($data[0])) {
            foreach ($data[0] as $key => $val) {
                View::assign($key, $val);
            }
        }
        if ($type == 1) {
            return $this->render();
        } elseif ($type == 2) {
            return $this->render('trademark_index');
        } elseif ($type == 3) {
            return $this->render('copyright_index');
        }
    }

    // /**
    //  * 添加或编辑
    //  * @return mixed
    //  * @throws \think\db\exception\DataNotFoundException
    //  * @throws \think\db\exception\DbException
    //  * @throws \think\db\exception\ModelNotFoundException
    //  * @author 牧羊人
    //  * @since 2020/7/2
    //  */
    // public function edit()
    // {
    //     if (IS_POST) {
    //         $url    = input("url","");
    //         $name   = input("url_name","");
    //         $status   = input("status",0);
    //         $result = false;
    //         $msg = '';
    //         if(empty($url)){
    //             return message("上传文件不能为空", false);
    //         }
    //         if(!empty($url)){
    //             $zip = new \app\common\model\Zipdown;
    //             $url_arr = explode(",",$url);
    //             $name_arr = explode(",",$name);
    //             if(count($url_arr) >= 1){
    //                 $datas = [];
    //                 foreach ($url_arr as $key => $value) {
    //                     $file = app()->getRootPath()."public/uploads".$value;
    //                     $arr = explode(".",$value);
    //                     $path = app()->getRootPath().'public/uploads'.$arr[0];
    //                     $zip->unzip_file($file,$path);
    //                     $arr_list = $this->scandirFolder($path);
    //                     $arr_file = $this->scandirFile($path,$arr[0]);

    //                     $names = explode(".",$name_arr[$key]);
    //                     $inside_number = $names[0];
    //                     $patent = Db::name("of_patent")->where("inside_number",$names[0])->find();
    //                     if(!empty($patent)){
    //                         if($status==2 && !empty($patent['issue_date']) && !empty($patent['number']) && !empty($patent['apply_date'])){
    //                             $this->monitor->monitor($patent['id']);
    //                         }
    //                     }else{
    //                         $msg .= "\n $inside_number : 未找到对应专利";
    //                         return message($msg, false);
    //                     }
    //                     $wh = [];
    //                     $wh[] = ['url_name','=',$inside_number];
    //                     $wh[] = ['status','=',$status];
    //                     $info = Db::name("of_patent_notice")->where($wh)->find();
    //                     if(!empty($info)){
    //                         continue;
    //                     }
    //                     $data = [];
    //                     $data['company_id'] = $patent['company_id'];
    //                     $data['url_name']   = $inside_number;
    //                     $data['url']        = $value;
    //                     $data['file']       = $arr_file;
    //                     $data['status']     = $status;
    //                     $datas[] = $data;
    //                 }
    //                 if(!empty($datas)){
    //                     $result = Db::name("of_patent_notice")->insertAll($datas);
    //                 }else{
    //                     return message("没有有效数据", false);
    //                 }
    //             }
    //         }
    //         return message("保存成功".$msg, true, $result);
    //     }
    //     $info = [];
    //     $id = input("get.id", 0);
    //     $contractInfo = "";
    //     if ($id) {
    //         $info = $this->model->getInfo($id);
    //         if(!empty($info['contract_id'])){
    //             $contractInfo = Db::name("of_contract")->where("id",$info['contract_id'])->find();
    //         }
    //     } else {
    //         $data = func_get_args();
    //         if (isset($data[0])) {
    //             foreach ($data[0] as $key => $val) {
    //                 $info[$key] = $val;
    //             }
    //         }
    //     }
    //     View::assign("contractInfo", $contractInfo);
    //     View::assign("info", $info);
    //     $statusList = [
    //         // '0' => '未提交',
    //         // '1' => '已提交',
    //         '2' => '授权未缴费',
    //         '3' => '已缴申请费',
    //         '4' => '初审合格',
    //         '5' => '公布及进实审',
    //         '6' => '已公布',
    //     ];
    //     View::assign("statusList", $statusList);
    //     return $this->render();
    // }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 牧羊人
     * @since 2020/7/2
     */
    public function edit()
    {
        if (IS_POST) {
            $url  = input("url", "");
            $name = input("url_name", "");

            $result = false;
            $msg    = '';
            if (empty($url)) {
                return message("上传文件不能为空", false);
            }

            //type patent_id
            $type      = input("type", "");
            $patent_id = input("patent_id", "");

            $url_arr  = explode(",", $url);
            $name_arr = explode(",", $name);

            if ($type == 1) {
                //专利的时候有 状态
                $new_status = input('new_status', 0);

                $zip = new \app\common\model\Zipdown;
                if (count($url_arr) >= 1) {
                    $datas       = [];
                    $save_data   = [];
                    $patent_data = [];
                    foreach ($url_arr as $key => $value) {
                        if (!strpos($name_arr[$key], "(") && !strpos($name_arr[$key], ".")) {
                            $msg .= "\n $name_arr[$key] : 文件名格式错误";
                            return message($msg, false);
                        }
                        //此处 为zip / pdf双支持
                        $arr_file = $value;

                        $type = pathinfo($value);
                        $type = strtolower($type["extension"]);
                        if ($type == 'zip') {
                            $file = app()->getRootPath() . "public/uploads" . $value;
                            $arr  = explode(".", $value);
                            $path = app()->getRootPath() . 'public/uploads' . $arr[0];
                            $zip->unzip_file($file, $path);
                            $arr_list = $this->scandirFolder($path);
                            $arr_file = $this->scandirFile($path, $arr[0]);
                        }

                        //通知书名称为 TZ2121245(通知书).zip   或者  TZ2121245.zip
                        //切割最后一个 （

                        if(strpos($name_arr[$key], "(")){
                            $lastSpace = strrpos($name_arr[$key], '(');
                            $str1      = trim(substr($name_arr[$key], 0, $lastSpace));
                            $str2      = trim(substr($name_arr[$key], $lastSpace));
                            $str2      = substr($str2, 1);
                            $names     = array($str1, $str2);
                        }else{
                            $lastSpace = strrpos($name_arr[$key], '.');
                            $str1      = trim(substr($name_arr[$key], 0, $lastSpace));
                            $str2      = trim(substr($name_arr[$key], $lastSpace));
                            $str2      = substr($str2, 1);
                            $names     = array($str1, $str2);
                        }
                        

                        $inside_number = $names[0];
                        if ($patent_id) {
                            $patent = Db::name("of_patent")->where("id", $patent_id)->where('mark', 1)->find();
                        } else {
                            $patent = Db::name("of_patent")->where("number", $names[0])->where('mark', 1)->find();
                        }

                        if (!empty($patent)) {
                            //单独上传不去验证 因为是挂靠在它下
                            if (!$patent_id) {
                                $patent_count = Db::name("of_patent")->where("patent_name", $names[0])->where('mark', 1)->count();
                                if ($patent_count > 1) {
                                    $msg .= "\n $inside_number : 该案件号存在多个请单独上传";
                                    return message($msg, false);
                                }

                                //检测是否存在通知书
                                $check_is_set_map = [
                                    ['mark','=',1],
                                    ['url_name','=',$name_arr[$key]],
                                    ['type','=',1],
                                    ['patent_id','=',$patent['id']],
                                ];

                                $check_is_set = $this->model->where($check_is_set_map)->value('id');
                                if($check_is_set){
                                    $msg .= "\n $inside_number : 已存在通知书";
                                    return message($msg, false);
                                }
                            }


                            // if ($status == 7 && !empty($patent['issue_date']) && !empty($patent['number']) && !empty($patent['apply_date'])) {
                            //     $this->monitor->monitor($patent['id']);
                            // }
                        } else {
                            $msg .= "\n $inside_number : 未找到对应专利";
                            return message($msg, false);
                        }

                        //检测 状态大于27 的时候是否存在发文日
                        // if($new_status >= 27){
                        //     if(!$patent['issue_date']){
                        //         $msg .= "\n $inside_number : 选择授权后的状态（该专利未填写发文日）";
                        //         return message($msg, false);
                        //     }
                        // }

                        $data               = [];
                        $data['company_id'] = $patent['company_id'];
                        $data['url_name']   = $name_arr[$key];
                        $data['url']        = $value;
                        $data['file']       = $arr_file;
                        $data['status']     = $new_status;
                        $data['patent_id']  = $patent['id'];
                        $datas[]            = $data;

                        $patent_data[] = [
                            'id'     => $patent['id'],
                            'new_status' => $new_status,
                        ];

                    }
                }
                if (empty($datas)) {
                    return message("没有有效数据", false);
                }
                if (!empty($datas)) {
                    $result = Db::name("of_patent_notice")->insertAll($datas);
                    $res    = $this->patentModel->saveAll($patent_data);
                }

            } elseif ($type == 2) {
                if (count($url_arr) >= 1) {
                    $datas       = [];
                    $patent_data = [];
                    foreach ($url_arr as $key => $value) {
                        if (!strpos($name_arr[$key], "-")) {
                            $msg .= "\n $name_arr[$key] : 文件名格式错误";
                            return message($msg, false);
                        }

                        $names = explode("-", $name_arr[$key]);

                        if (count($names) != 3) {
                            $msg .= "\n $name_arr[$key] : 文件名格式错误理论上该是 xx-xxxx-xx.pdf";
                            return message($msg, false);
                        }

                        if (strpos($names[0], "商标注册申请受理通知书") !== false || strpos($names[1], "商标注册申请受理通知书") !== strpos($names[2], "商标注册申请受理通知书")) {
                            //如果状态字眼包含有   商标注册申请受理通知书  申请程序
                            $status = 1;
                        } elseif (strpos($names[0], "商标注册证") !== false || strpos($names[1], "商标注册证") !== strpos($names[2], "商标注册证")) {
                            //如果状态带有 商标注册证   注册公告
                            $status = 5;
                        } elseif (strpos($names[0], "商标驳回通知书") !== false || strpos($names[1], "商标驳回通知书") !== strpos($names[2], "商标驳回通知书")) {
                            //如果状态带有 商标驳回通知书 全部驳回
                            $status = 3;
                        }if (strpos($names[0], "商标部分驳回通知书") !== false || strpos($names[1], "商标部分驳回通知书") !== strpos($names[2], "商标部分驳回通知书")) {
                            //如果状态带有 商标部分驳回通知书 部分驳回
                            $status = 2;
                        } elseif (strpos($names[0], "初步审定通知书") !== false || strpos($names[1], "初步审定通知书") !== strpos($names[2], "初步审定通知书")) {
                            //如果状态带有 初步审定通知书 初审公告
                            $status = 4;
                        }
                        if ($patent_id) {
                            $rademark = Db::name('of_trademark')->find($patent_id);
                        } else {
                            $apply_number = '';
                            if (is_numeric($names[0])) {
                                $apply_number = $names[0];
                            }
                            if (is_numeric($names[1])) {
                                $apply_number = $names[1];
                            }
                            if (is_numeric($names[2])) {
                                $apply_number = $names[2];
                            }

                            if (!$apply_number) {
                                $msg .= "\n $name_arr[$key] : 文件名格式错误 未包含商标唯一标识 申请号";
                                return message($msg, false);
                            }
                            $rademark = Db::name('of_trademark')->where('apply_number', $apply_number)->where('mark', 1)->find();
                        }

                        //假设不存在 返回错误
                        if (!$rademark) {
                            $msg .= "\n $name_arr[$key] : 未查找到对应的商标";
                            return message($msg, false);
                        }

                        //不限制 一直上传（重复建议自己删除）
                        // $wh = [];
                        // $wh[] = ['url_name','=',$name_arr[$key]];  //名字全
                        // $wh[] = ['status','=',$status];

                        $data               = [];
                        $data['company_id'] = $rademark['company_id']; //客户id
                        $data['url_name']   = $name_arr[$key];
                        $data['url']        = $value;
                        $data['file']       = $value;
                        $data['status']     = $status;
                        $data['type']       = 2;
                        $data['patent_id']  = $rademark['id']; //此为商标id
                        $datas[]            = $data;

                        //如果 状态为5 注册公告  则不更改状态
                        if ($rademark['status'] != 5) {
                            $patent_data[] = [
                                'id'     => $rademark['id'],
                                'status' => $status,
                            ];
                        }

                    }
                    if (empty($datas)) {
                        return message("没有有效数据", false);
                    }
                    if (!empty($datas)) {
                        $result = Db::name("of_patent_notice")->insertAll($datas);

                        $result = $this->tradeModel->saveAll($patent_data);
                    }
                }
            } elseif ($type == 3) {
                if (count($url_arr) >= 1) {
                    $datas = [];
                    foreach ($url_arr as $key => $value) {

                        if ($patent_id) {
                            $copyright = Db::name('of_copyright')->find($patent_id);
                        } else {

                        }

                        //假设不存在 返回错误
                        if (!$copyright) {
                            $msg .= "未查找到对应的著作权";
                            return message($msg, false);
                        }

                        $data               = [];
                        $data['company_id'] = $copyright['company_id']; //客户id
                        $data['url_name']   = $name_arr[$key];
                        $data['url']        = $value;
                        $data['file']       = $value;
                        $data['status']     = 0;
                        $data['type']       = 3;
                        $data['patent_id']  = $patent_id; //此为商标id
                        $datas[]            = $data;

                    }
                    if (empty($datas)) {
                        return message("没有有效数据", false);
                    }
                    if (!empty($datas)) {
                        $result = Db::name("of_patent_notice")->insertAll($datas);
                    }
                }
            }
            return message("保存成功" . $msg, true, $result);
        }
        $info         = [];
        $id           = input("get.id", 0);
        $contractInfo = "";
        if ($id) {
            $info = $this->model->getInfo($id);
            if (!empty($info['contract_id'])) {
                $contractInfo = Db::name("of_contract")->where("id", $info['contract_id'])->find();
            }
        } else {
            $data = func_get_args();
            if (isset($data[0])) {
                foreach ($data[0] as $key => $val) {
                    $info[$key] = $val;
                }
            }
        }
        $patent_id = input("patent_id", 0);
        $type      = input("type"); //type在各自引用的时候url带上  专利的type 未带 但是在index 默认填入1

        View::assign("contractInfo", $contractInfo);
        View::assign("info", $info);

        $newStatusList = config('admin.patentnotice_status_2');
        View::assign('newStatusList', $newStatusList);

        View::assign('type', $type);
        View::assign('patent_id', $patent_id);
        return $this->render();
    }

/**
 * @date: 2022/1/4 0002
 * @describe:打包下载
 */
    public function download()
    {
        $ids = $this->request->param("ids");
        if (!is_array($ids)) {
            $ids = @explode(",", $ids);
        }
        $data = $this->model->field("url_name,file,status,id")->where('id', 'in', $ids)->select()->toArray();

        if (!empty($data)) {
            $zip     = new \app\common\model\Zipdown;
            $zip_arr = [];
            foreach ($data as $key => $value) {
                $da   = [];
                $down = explode(",", $value['file']);
                foreach ($down as $k => $val) {
                    // $dir_name = Db::name("of_patent")->where("inside_number",$value['url_name'])->value("patent_name");
                    // if(!empty($dir_name)){
                    //     if($value['status'] == 1){
                    //         $dir_name .= "-已提交";
                    //     }else if($value['status'] == 2){
                    //         $dir_name .= "-授权未缴费";
                    //     }else if($value['status'] == 3){
                    //         $dir_name .= "-已缴申请费";
                    //     }else if($value['status'] == 4){
                    //         $dir_name .= "-初审合格";
                    //     }else if($value['status'] == 5){
                    //         $dir_name .= "-公布及进实审";
                    //     }else if($value['status'] == 6){
                    //         $dir_name .= "-已公布";
                    //     }else{
                    //         $dir_name .= "-未提交";
                    //     }
                    // }
                    $dir_name   = $this->model->where("id", $value['id'])->value("url_name");
                    $da['url']  = $val;
                    $da['name'] = $dir_name;
                    $zip_arr[]  = $da;
                }
            }
            $filename = $zip->zipfile($zip_arr, count($data) > 1 ? '通知书批量文件' : '通知书文件');

            //打包下载
            if (!empty($filename)) {
                $msg = message("执行成功", true, ['filename' => $filename]);
            } else {
                $msg = message("暂无数据", false);
            }
        } else {
            $msg = message("暂无数据", false);
        }
        return json_encode($msg);
    }

/*
 * 递归获取文件夹和文件
 * @param   $path 获取的文件夹路径
 * @return  $list array
 * 使用scandir函数可以扫描文件夹下内容 代替while循环读取
 */
    public function scandirFolder($path, $dir = '', $fix_dir = '')
    {
        $list = [];
        if ($fix_dir == '') {
            $fix_dir = $path;
        }
        $temp_list = scandir($path);
        foreach ($temp_list as $file) {
            if ($file != ".." && $file != ".") {
                if (is_dir($path . "/" . $file)) {
                    //子文件夹，进行递归
                    $list[][$file] = $this->scandirFolder($path . "/" . $file, $dir . '/' . $file, $fix_dir);
                } else {
                    //根目录下的文件
                    if (strpos($file, 'tif') !== false || strpos($file, 'pdf') !== false) {
                        $arr_file = explode("\\", $file);
                        @copy($fix_dir . $dir . '/' . $file, $fix_dir . '/' . end($arr_file));
                        $list[] = $dir . '/' . end($arr_file);
                    }
                }

            }
        }
        return $list;
    }

/*
 * 递归获取多维数组的内容
 * @param   $arr 数组
 * @return  $arr array
 */
    public function scandirFile($path, $dir)
    {
        $list      = [];
        $temp_list = scandir($path);
        foreach ($temp_list as $file) {
            if ((strpos($file, 'tif') !== false || strpos($file, 'pdf') !== false) && strpos($file, '\\') === false) {
                $list[] = $dir . '/' . $file;
            }
        }
        return implode(',', $list);
    }

}
